#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
完整系统启动脚本
同时启动爬虫和Web展示服务
"""

import subprocess
import time
import signal
import sys
import os
import threading
from datetime import datetime
import re

class FullSystemRunner:
    def __init__(self):
        self.spider_process = None
        self.web_process = None
        self.running = True
        
        # 设置信号处理
        signal.signal(signal.SIGINT, self.signal_handler)
        signal.signal(signal.SIGTERM, self.signal_handler)
    
    def signal_handler(self, signum, frame):
        """处理退出信号"""
        print(f"\n收到退出信号 {signum}，正在停止系统...")
        self.running = False
        self.stop_all_processes()
        sys.exit(0)
    
    def start_spider(self):
        """启动持续爬虫"""
        print("=== 启动持续爬虫 ===")
        
        try:
            # 获取当前脚本所在目录
            current_dir = os.path.dirname(os.path.abspath(__file__))
            print(f"当前目录: {current_dir}")
            
            # 检查爬虫脚本是否存在
            spider_script = os.path.join(current_dir, 'run_continuous_spider.py')
            if not os.path.exists(spider_script):
                print(f"✗ 爬虫脚本不存在: {spider_script}")
                return False
            
            print(f"找到爬虫脚本: {spider_script}")
            
            # 启动持续爬虫 - 改为10分钟间隔
            cmd = ['python3.8', spider_script, '-i', '10']
            self.spider_process = subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                cwd=current_dir  # 设置工作目录
            )
            
            print(f"✓ 持续爬虫已启动，PID: {self.spider_process.pid}")
            return True
            
        except Exception as e:
            print(f"✗ 启动爬虫失败: {e}")
            return False
    
    def start_web_dashboard(self):
        """启动Web仪表板"""
        print("=== 启动Web仪表板 ===")
        
        try:
            # 获取当前脚本所在目录
            current_dir = os.path.dirname(os.path.abspath(__file__))
            print(f"当前目录: {current_dir}")
            
            # 检查Web脚本是否存在
            web_script = os.path.join(current_dir, 'simple_web_dashboard.py')
            if not os.path.exists(web_script):
                print(f"✗ Web脚本不存在: {web_script}")
                return False
            
            print(f"找到Web脚本: {web_script}")
            
            # 启动Web服务
            cmd = ['python3.8', web_script, '--host', '0.0.0.0', '--port', '5000']
            self.web_process = subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                cwd=current_dir  # 设置工作目录
            )
            
            print(f"✓ Web仪表板已启动，PID: {self.web_process.pid}")
            print(f"✓ 访问地址: http://localhost:5000")
            return True
            
        except Exception as e:
            print(f"✗ 启动Web仪表板失败: {e}")
            return False
    
    def monitor_processes(self):
        """监控进程状态"""
        while self.running:
            try:
                # 检查爬虫进程
                if self.spider_process and self.spider_process.poll() is not None:
                    print("⚠️ 爬虫进程已停止，尝试重启...")
                    if not self.start_spider():
                        print("✗ 爬虫重启失败")
                
                # 检查Web进程
                if self.web_process and self.web_process.poll() is not None:
                    print("⚠️ Web进程已停止，尝试重启...")
                    if not self.start_web_dashboard():
                        print("✗ Web重启失败")
                
                time.sleep(30)  # 每30秒检查一次
                
            except Exception as e:
                print(f"监控进程时出错: {e}")
                time.sleep(10)
    
    def stop_all_processes(self):
        """停止所有进程"""
        print("正在停止所有进程...")
        
        if self.spider_process:
            try:
                self.spider_process.terminate()
                self.spider_process.wait(timeout=10)
                print("✓ 爬虫进程已停止")
            except:
                self.spider_process.kill()
                print("✓ 爬虫进程已强制停止")
        
        if self.web_process:
            try:
                self.web_process.terminate()
                self.web_process.wait(timeout=10)
                print("✓ Web进程已停止")
            except:
                self.web_process.kill()
                print("✓ Web进程已强制停止")
    
    def run(self):
        """运行完整系统"""
        print("=== 惠农网农产品价格监控系统 ===")
        print(f"启动时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print("按 Ctrl+C 停止系统")
        print()
        
        # 启动爬虫
        if not self.start_spider():
            print("爬虫启动失败，系统退出")
            return
        
        # 等待爬虫初始化
        time.sleep(5)
        
        # 启动Web仪表板
        if not self.start_web_dashboard():
            print("Web仪表板启动失败，但爬虫仍在运行")
        
        # 启动监控线程
        monitor_thread = threading.Thread(target=self.monitor_processes, daemon=True)
        monitor_thread.start()
        
        print("\n=== 系统启动完成 ===")
        interval = self.get_real_interval()
        print(f"✓ 持续爬虫: 每{interval}秒运行一次")
        print("✓ Web仪表板: http://localhost:5000")
        print("✓ 数据存储: Redis (192.168.88.130:6379)")
        print("✓ 自动监控: 进程状态监控中")
        print("\n系统正在运行中...")
        
        try:
            # 保持主线程运行
            while self.running:
                time.sleep(1)
        except KeyboardInterrupt:
            print("\n收到中断信号...")
        finally:
            self.stop_all_processes()
            print("=== 系统已停止 ===")

    def get_real_interval(self):
        try:
            with open('run_continuous_spider.py', 'r', encoding='utf-8') as f:
                code = f.read()
            # 优先查找interval_seconds
            m = re.search(r'def __init__\(self, interval_seconds=(\d+)\)', code)
            if m:
                return int(m.group(1))
            # 其次查找interval_minutes
            m = re.search(r'def __init__\(self, interval_minutes=(\d+)\)', code)
            if m:
                return int(m.group(1)) * 60
            # 查找命令行参数默认值
            m = re.search(r'parser\.add_argument\([^)]+default=(\d+)', code)
            if m:
                return int(m.group(1))
        except Exception as e:
            print(f"[警告] 自动检测调度间隔失败: {e}")
        return 600  # 默认10分钟

def main():
    import argparse
    
    parser = argparse.ArgumentParser(description='惠农网农产品价格监控系统')
    parser.add_argument('--spider-only', action='store_true', help='仅启动爬虫')
    parser.add_argument('--web-only', action='store_true', help='仅启动Web服务')
    
    args = parser.parse_args()
    
    runner = FullSystemRunner()
    
    if args.spider_only:
        # 仅启动爬虫
        if runner.start_spider():
            print("爬虫已启动，按 Ctrl+C 停止")
            try:
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                runner.stop_all_processes()
    elif args.web_only:
        # 仅启动Web服务
        if runner.start_web_dashboard():
            print("Web服务已启动，按 Ctrl+C 停止")
            try:
                while True:
                    time.sleep(1)
            except KeyboardInterrupt:
                runner.stop_all_processes()
    else:
        # 启动完整系统
        runner.run()

if __name__ == '__main__':
    main() 